/**
 * @project mybatisDemo_zkingbbsxiugai
 * @Title PersonalController.java
 * @description 
 * @Package org.qiuqiu.controller
 * @author wangsongmao  email:wangsongmao@zkingsoft.com
 * @date  2015年5月15日 下午10:59:05
 * 
 */
package org.qiuqiu.controller;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.qiuqiu.service.PostService;
import org.qiuqiu.service.UserService;
import org.qiuqiu.utils.MD5Utils;
import org.qiuqiu.utils.SendEmailUtils;
import org.qiuqiu.vo.PaginationVO;
import org.qiuqiu.vo.Post;
import org.qiuqiu.vo.Reply;
import org.qiuqiu.vo.User;
import org.qiuqiu.vo.UserExample;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

/**
 * @project mybatisDemo_zkingbbsxiugai
 * @Title PersonalController.java
 * @Package org.qiuqiu.controller
 * @author wangsongmao email:wangsongmao@zkingsoft.com
 * @date 2015年5月15日 下午10:59:05
 */
@Controller
@RequestMapping("/personal")
public class PersonalController {
	private Logger log = Logger.getLogger(this.getClass());
	@Autowired
	private UserService userService;
	@Autowired
	private PostService postService;

	@RequestMapping(value = "/update", method = { RequestMethod.POST,
			RequestMethod.GET })
	public String form(
			@RequestParam(value = "file", required = false) MultipartFile file,
			Model model, HttpServletRequest rs) {
		/* System.out.println("我能得到的路径："+rs.getContextPath()); */
		String basePath = rs.getScheme() + "://" + rs.getServerName() + ":"
				+ rs.getServerPort() + rs.getContextPath() + "/";
		/* System.out.println("lijiqwiwer==er "+basePath); */
		if (!file.isEmpty()) {
			/*
			 * System.out.println("文件的大小："+file.getSize());
			 * System.out.println("文件的类型："+file.getContentType());
			 * System.out.println("文件的原始名字："+file.getOriginalFilename());
			 * System.out.println("文件的名字："+file.getName());
			 */

			SimpleDateFormat f = new SimpleDateFormat("yyyyMMddHHmm");

			String realpath = rs.getSession().getServletContext()
					.getRealPath("/");
			File f1 = new File(realpath);
			if (!f1.exists()) {
				f1.mkdir();
			}

			/*
			 * String
			 * hzhui=file.getOriginalFilename().substring(file.getOriginalFilename
			 * ().lastIndexOf("."));
			 */
			/* String filename=+file.getOriginalFilename(); */
			/*
			 * System.out.println("我能得到的路径："+rs.getSession().getServletContext().
			 * getRealPath("/static"));
			 */
			basePath = basePath + "upload/head/" + f.format(new Date())
					+ file.getOriginalFilename();

			try {
				FileUtils.copyInputStreamToFile(
						file.getInputStream(),
						new File(realpath, "upload/head/"
								+ f.format(new Date())
								+ file.getOriginalFilename()));
				User user = (User) rs.getSession().getAttribute("user");
				user.setImg(basePath);
				userService.updateByPrimaryKey(user);
				rs.getSession().setAttribute("user", user);
				model.addAttribute("msg", "头像上传成功！");
			} catch (IOException e) {
				model.addAttribute("msg", "头像上传失败！");
				e.printStackTrace();
			}
		}

		return "personal/update";

	}

	@RequestMapping(value = "/upload")
	public String update() throws Exception {
		return "personal/update";
	}

	@RequestMapping(value = "/resetpassword")
	public String retpassword() throws Exception {
		return "personal/retpassword";
	}

	@RequestMapping(value = "/checkpassword", method = RequestMethod.GET)
	public void checkpassword(@RequestParam("oldpassword") String oldpassword,
			HttpServletResponse re, HttpSession session) throws Exception {
		String flag = "no";
		User user = (User) session.getAttribute("user");
		if (user.getPassword().equals(MD5Utils.md5(oldpassword))) {
			flag = "ok";
		}
		JSONObject data = new JSONObject();
		data.put("flag", flag);
		re.setContentType("application/json; charset=utf-8");
		PrintWriter out = re.getWriter();
		out.write(data.toString());
		out.flush();
		out.close();
	}

	@RequestMapping(value = "/updatepassword", method = { RequestMethod.GET,
			RequestMethod.POST })
	public String updatepassword(User u, HttpSession session, Model model)
			throws Exception {
		if (u != null) {
			if (u.getPassword() != null) {
				User user = (User) session.getAttribute("user");
				user.setPassword(MD5Utils.md5(u.getPassword()));
				userService.updateByPrimaryKey(user);
				session.setAttribute("user", user);
				model.addAttribute("msg", "修改成功");

			}
		}
		return "personal/retpassword";

	}

	// 个人中心
	@RequestMapping(value = "/mypost")
	public String findmyPost(HttpSession session, Model m, PaginationVO page)
			throws Exception {
		User user = (User) session.getAttribute("user");
		List<Post> postList = postService.findAllPostByUser(user, page);
		System.out.println("我的帖子是" + postList);
		int total = postService.countPostByUser(user);
		page.setTotalField(total);
		/*
		 * List<Reply> replyList=replyService.findAllReplyByUser(user);
		 * System.out.println("我回复的帖子"+replyList);
		 */
		m.addAttribute("postList", postList);
		m.addAttribute("page", page);
		/* m.addAttribute("replyList", replyList); */
		return "/personal/mypost";
	}

	@RequestMapping(value = "/person")
	public String uploading() throws Exception {
		return "personal/personal";
	}

	@RequestMapping(value = "/isEmailExist", method = RequestMethod.GET)
	public void isEmail(@RequestParam("email") String email,
			HttpServletResponse re, HttpSession session) throws Exception {
		UserExample ex = new UserExample();
		ex.createCriteria().andEmailEqualTo(email);
		int flag = userService.countByExample(ex);
		JSONObject data = new JSONObject();
		data.put("flag", flag);
		re.setContentType("application/json; charset=utf-8");
		PrintWriter out = re.getWriter();
		out.write(data.toString());
		out.flush();
		out.close();
	}

	// 验证昵称是否存在
	@RequestMapping(value = "/isNickNameexsit", method = RequestMethod.GET)
	public void isNickNameexsit(@RequestParam("nickname") String nickname,
			HttpServletResponse re) throws Exception {
		UserExample ex = new UserExample();
		ex.createCriteria().andNicknameEqualTo(nickname);
		Integer flag = userService.countByExample(ex);
		JSONObject data = new JSONObject();
		data.put("flag", flag);
		re.setContentType("application/json; charset=utf-8");
		PrintWriter out = re.getWriter();
		out.write(data.toString());
		out.flush();
		out.close();
	}

	@RequestMapping(value = "/up", method = {RequestMethod.POST,RequestMethod.GET})
	public String up(User user, Model model, HttpSession session)
			throws Exception {
		if (user != null) {
			if (user.getEmail()!=null&&!"".equals(user.getEmail())&&user.getNickname()!=null&&!"".equals(user.getNickname())) {
				
			
			User u = (User) session.getAttribute("user");	
			u.setEmail(user.getEmail());
			u.setNickname(user.getNickname());
			if (!user.getEmail().equals(u.getEmail())) {
				  u.setStatus(0);
			}
			userService.updateByPrimaryKeySelective(u);			
			model.addAttribute("msg", "修改成功");
			session.setAttribute("user", u);
			}
		}
		return "personal/personal";

	}
	@RequestMapping(value = "/jh", method = RequestMethod.POST)
	public void jh(HttpSession session,
			HttpServletResponse re,HttpServletRequest rs)  {
		String flag="0";
		JSONObject 	data = new JSONObject();;
		PrintWriter out=null;
		try {
			re.setContentType("application/json; charset=utf-8");
			out = re.getWriter();
			User u = (User) session.getAttribute("user");
			SendEmailUtils.sendEmail(u, rs);
			flag="2";
		} catch (UnknownHostException e) {
		
			e.printStackTrace();
		} catch (IOException e) {
		
			e.printStackTrace();
		}finally{
		data.put("flag", flag);	
		out.write(data.toString());
		out.flush();
		out.close();
		}
	}
}
